<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\lose\controller;

use cmf\controller\AdminBaseController;
use app\lose\model\LosePostModel;
use app\lose\service\PostService;
use app\lose\model\LoseCategoryModel;
use think\Db;
use app\admin\model\ThemeModel;
use think\Image;


class AdminArticleController extends AdminBaseController
{
    /**
     * 文章列表
     * @adminMenu(
     *     'name'   => '文章管理',
     *     'parent' => 'lose/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $param               = $this->request->param();
        $categoryId          = $this->request->param('category', 0, 'intval');
        $ReceiveStatus       = $this->request->param('receive_status', 0, 'intval');
        $param['sort_by']    = $this->request->param('sort_by','','trim');
        $param['list_order'] = $this->request->param('list_order','DESC','trim');

        $loseCategoryModel = new LoseCategoryModel();
        $postService         = new PostService();
        $data                = $postService->adminArticleList($param);
        $articles            = $data->items();
        
        /**
         * 文章是否拥有编辑和删除的权限
         * 只要该文章所属的某个分类中拥有编辑或删除权限即可以操作该文章
         */
        $articleEdit    = cmf_auth_check(cmf_get_current_admin_id(), 'lose/adminarticle/edit');
        $articlesDelete = cmf_auth_check(cmf_get_current_admin_id(), 'lose/adminarticle/delete');
        
        $userId   = cmf_get_current_admin_id();
        $roleId   = session('ROLE_ID');
        foreach ($articles as $k => &$v) {
            // 审核节点
            // $audit_id = $loseCategoryModel->where('id',$v['category_id'])->value('audit_id');
            // if( $audit_id && $v['post_status'] != 99 && $v['post_status'] != -1 ){
            //     $where = [
            //         'audit_id'   => $audit_id, 
            //         'step_index' => $v['post_status'],
            //     ];
            //     $v['audit_node'] = db('audit_flow_step')->where($where)->value('step_name');
            // }

            // 若为超级管理员可编辑和删除
            if( $roleId == 1 ){
                $v['is_edit'] = $v['is_delete'] = 1;
            }else{
                $v['is_edit'] = $v['is_delete'] = 0;
                // 若不是超级管理员，仅可操作自己添加的文章
                // if( $v['user_id'] != $userId )           continue;
                if( !$articleEdit && !$articlesDelete )  continue;

                // 该文章所属的所有分类
                $categoryIds  = db('lose_category_post')->where('post_id', $v['id'])->column('category_id');
                if( $articleEdit ){
                    //文章审核状态为未通过才能编辑文章，待审核及审核通过均不允许编辑
                    // if( $v['post_status'] === -1 ){
                        // 该文章所属的某个分类是否拥有编辑的操作权限
                        $v['is_edit']   = check_cat_priv($categoryIds,'edit');
                    // }
                }

                if( $articlesDelete ){
                    // 该文章所属的某个分类是否拥有删除的操作权限
                    $v['is_delete']   = check_cat_priv($categoryIds,'delete');
                }
            }
        }
        
        //向分页追加请求参数
        $data->appends($param);

        //根据角色栏目权限生成分类树
        $idList       = get_cat_priv('init', 'lose_category'); //获取该角色可查看的栏目分类id
        $categoryTree = $loseCategoryModel->adminCategoryTree($categoryId, 0, $idList);

        //当前排序依据
        $sort_flag  = sort_flag($param);
        $this->assign($sort_flag['tag'], $sort_flag['img']);

        //获取列表项
        $listItem = get_list_item_column('lose_post');
        $this->assign('list_item', $listItem);

        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('articles', $articles);
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign("filter",$param);
        $this->assign("ReceiveStatus",$ReceiveStatus);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    /**
     * 添加文章
     * @adminMenu(
     *     'name'   => '添加文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        //当前分类信息
        $categoryId = $this->request->param('category', 0, 'intval');

        //判断该分类下是否拥有添加文章权限
        if( !empty($categoryId) ){
            if( !check_cat_priv($categoryId, 'add') ){
                $this->error(lang('NO_AUTH'));
            }
        }

        $category   = Db::name('LoseCategory')
                   -> field('id,name,parent_id,list_tpl,thumb_size,taxonomy')
                   -> find($categoryId);
        $category['name'] = empty($category['name']) ? '' :$category['name'];
        $category['id']   = empty($category['id']) ? '' :$category['id'];

        //分类类型
        $taxonomy         = empty($category['taxonomy']) ? 'article' : $category['taxonomy'] ;
        
        //分类缩略图推荐尺寸
        if( empty($category['thumb_size']) && !empty($category['parent_id']) ){
            $category['thumb_size'] = get_thumb_size($category['parent_id']);
        }

        // 该文章所属分类的类型(文章，pdf，视频，图片等)的数据字段
        $field_list = Db::name('Field')
                   -> alias('f')
                   -> join('__MODULE__ m ','f.relatedid = m.id','LEFT')
                   -> where( array('m.name' => $taxonomy) )
                   -> column('fieldname');

        // 是否有状态字段
        foreach ($field_list as $k => $v) {
            if( substr($v,0,7) === 'status_' ){
                $field_status_list[] = $v;
            }
        }
        // pre($field_list);

        /*分类树(文章所属分类-单选)*/
        $idList              = get_cat_priv('add', 'lose_category');
        $loseCategoryModel = new LoseCategoryModel();
        $categoryTree        = $loseCategoryModel->adminCategoryTree($categoryId, 0, $idList);
        $this->assign('category_tree', $categoryTree);

        //获取文章详情页模版列表
        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('lose/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);   //文章详情页模版列表

        //维修人员-单选
        $member_list = Db::name('member')->where(['user_type'=>2])->select();
        $this->assign('member_list', $member_list);

        $this->assign('category', $category);                       //分类信息
        $this->assign("field_list", $field_list);                   //该分类类型的字段
        $this->assign("field_status_list", $field_status_list);     //该分类类型的状态字段

        return $this->fetch();
    }

    /**
     * 添加文章提交
     * @adminMenu(
     *     'name'   => '添加文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {   

        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }

            $losePostModel = new LosePostModel();

            // 相册
            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            // 附件
            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }
          
            $losePostModel->adminAddArticle($data['post'], $data['post']['categories']);

            $data['post']['id'] = $losePostModel->id;
            $hookParam          = [
                'is_add'  => true,
                'article' => $data['post']
            ];
            hook('lose_admin_after_save_article', $hookParam);

            //操作日志
            admin_log($post['post_title'], 'add', 'article');

            $this->success('添加成功!', url('AdminArticle/edit', ['id' => $losePostModel->id]));
        }

    }

    /**
     * 编辑文章
     * @adminMenu(
     *     'name'   => '编辑文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');

        if( session('ROLE_ID') != 1 ){
            //获取关联的分类id
            $cat_id_list = Db::name('lose_category_post')->where(['post_id'=>$id])->column('category_id');
            if( !check_cat_priv($cat_id_list, 'edit') ){
                $this->error(lang('NO_AUTH'));
            }
        }

        //文章信息
        $losePostModel = new LosePostModel();
        $post            = $losePostModel->where('id', $id)->find();

        if ($post['receive_time']) {
            $post['receive_time'] = date('Y-m-d H:i:s',$post['receive_time']);
        }else{
            $post['receive_time'] = '';
        }
        

        //文章所属分类信息
        $Categories  = $post
                    -> categories()
                    -> alias('a')
                    -> field('a.name,a.id,thumb_size,list_tpl,taxonomy,parent_id')
                    -> select();
        foreach ($Categories as $k => $v) {
            // $postCategoryIds[] = $v['id'];          //文章所属分类id集合
            // $postCategories[]  = $v['name'];        //文章所属分类名集合
            
            $taxonomy[$v['taxonomy']] = $v['taxonomy'];  //用于查询该分类类型拥有的字段
            if( empty($v['thumb_size']) ){
                $Categories[$k]['thumb_size'] = get_thumb_size($v['parent_id']);
            }
        }

        // 该文章所属分类的类型(文章，pdf，视频，图片等)拥有的数据字段
        $field_list = Db::name('Field')
                      -> alias('f')
                      -> join('__MODULE__ m ','f.relatedid = m.id','LEFT')
                      -> where( array('m.name' => array('IN',$taxonomy) ) )
                      -> column('fieldname');
        // 是否有状态字段
        foreach ($field_list as $k => $v) {
            if( substr($v,0,7) === 'status_' ){
                $field_status_list[] = $v;
            }
        }

        $siteConfig = cmf_get_site_info();
        $authMode   = $siteConfig['auth_mode'];

        //分类树(文章所属分类-单选)
        $idList              = get_cat_priv('edit', 'lose_category');
        $loseCategoryModel = new LoseCategoryModel();
        $categoryTree        = $loseCategoryModel->adminCategoryTree($Categories[0]['id'], 0, $idList);
        $this->assign('category_tree', $categoryTree);


        //详情页模版列表
        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('lose/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);   //详情页模版列表
    // pre($post->toArray());die;
        $this->assign('post', $post);                               //文章信息
        $this->assign('categories', $Categories);                   //文章信息
        $this->assign("field_list", $field_list);                   //该分类类型的字段
        $this->assign("field_status_list", $field_status_list);     //该分类类型的状态字段

        return $this->fetch();
    }

    /**
     * 编辑文章提交
     * @adminMenu(
     *     'name'   => '编辑文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }
            $data['post']['receive_time'] = strtotime($post['receive_time']);

            // pre($data['post']);die;

            if ($data['post']['receive_status'] == 1) {
                $data['post']['receive_person'] = '';
                $data['post']['receive_mobile'] = '';
                $data['post']['receive_time'] = '';
            }


            //如果选择已领取，则判断是否填写了领取人信息
            if ($data['post']['receive_status'] == 2) {
                if ($data['post']['receive_person'] == '' or $data['post']['receive_mobile'] == '' or $data['post']['receive_time'] == '') {
                    $this->error('请填写领取人、联系电话、领取时间');
                }
            }

            $categories = $post['categories'];
          
            if($categories){
                $categories = explode(',',$categories);
            }

            $losePostModel = new LosePostModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            // pre($data['post']);die;

            $losePostModel->adminEditArticle($data['post'], $data['post']['categories']);

            $hookParam = [
                'is_add'  => false,
                'article' => $data['post']
            ];
            hook('lose_admin_after_save_article', $hookParam);

            //操作日志
            admin_log($post['post_title'], 'edit', 'article');


            $this->success('保存成功!');

        }
    }

    /**
     * 文章删除
     * @adminMenu(
     *     'name'   => '文章删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $param           = $this->request->param();
        $losePostModel = new LosePostModel();
        $siteConfig      = cmf_get_site_info();
        $authMode        = $siteConfig['auth_mode'];

        if (isset($param['id'])) {
            $id           = $this->request->param('id', 0, 'intval');

            if( session('ROLE_ID')!=1 ){
                //获取关联的分类id
                $cat_id_list = Db::name('lose_category_post')->where(['post_id'=>$id])->column('category_id');

                //只要文章所属的某个分类拥有删除权限，即可以操作该文章
                if( !check_cat_priv($cat_id_list, 'delete') ){
                    $this->error(lang('NO_AUTH'));
                }
            }

            $result = $losePostModel->where(['id' => $id])->find();
            $data   = [
                'object_id'   => $result['id'],
                'create_time' => time(),
                'table_name'  => 'lose_post',
                'name'        => $result['post_title'],
                'site_id'     => $result['site_id'],  //站点ID
            ];
            $resultLose = $losePostModel
                         -> where(['id' => $id])
                         -> update(['delete_time' => time()]);
            if ($resultLose) {
                Db::name('recycleBin')->insert($data);
            }

            //操作日志
            admin_log($result['post_title'], 'delete', 'article');

            $this->success("删除成功！", '');
        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $recycle = $losePostModel->where(['id' => ['in', $ids]])->select();
            $result  = false;

            //若是超级管理员，直接删除接收到的文章id;否则只删除该角色拥有的分类删除权限下的文章
            if( session('ROLE_ID')==1 ){
                $result  = $losePostModel->where(['id' => ['in', $ids]])->update(['delete_time' => time()]);
            }else{
                $user_id = cmf_get_current_admin_id();
                foreach($recycle as $key=>$value){

                    // if( $user_id == $value['user_id'] ){
                        //文章所属的所有分类id
                        $cat_id_list = Db::name('lose_category_post')->where(['post_id'=>$value['id']])->column('category_id');

                        //检查是否拥有删除权限，只要文章所属分类的某个分类拥有删除权限，则可以操作该文章
                        if( check_cat_priv($cat_id_list, 'delete') ){
                            //组合新的要删除的文章id
                            $new_ids[] = $value['id'];
                        }else{
                            unset($recycle[$key]);    
                        }
                    // }else{
                        // unset($recycle[$key]);
                    // }
                }

                if( !empty($new_ids) ){
                    $result = $losePostModel->where(['id' => ['in', $new_ids]])->update(['delete_time' => time()]);
                }
            }

            //更新文章删除时间成功，加入回收站
            if ($result) {
                foreach ($recycle as $value) {
                    $data = [
                        'object_id'   => $value['id'],
                        'create_time' => time(),
                        'table_name'  => 'lose_post',
                        'name'        => $value['post_title'],
                        'site_id'     => $value['site_id'],  //站点ID
                    ];
                    Db::name('recycleBin')->insert($data);
                }

                //操作日志
                admin_log('', 'batch_delete', 'article');

                $this->success("删除成功！", '');
            }else{
                $this->success("删除失败！", '');
            }
        }
    }

    /**
     * 文章发布
     * @adminMenu(
     *     'name'   => '文章发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章发布',
     *     'param'  => ''
     * )
     */
    // public function publish()
    // {
    //     $param           = $this->request->param();
    //     $losePostModel = new LosePostModel();

    //     if (isset($param['ids']) && isset($param["yes"])) {
    //         $ids = $this->request->param('ids/a');

    //         $losePostModel->where(['id' => ['in', $ids]])->update(['post_status' => 1, 'published_time' => time()]);

    //         $this->success("发布成功！", '');
    //     }

    //     if (isset($param['ids']) && isset($param["no"])) {
    //         $ids = $this->request->param('ids/a');

    //         $losePostModel->where(['id' => ['in', $ids]])->update(['post_status' => 0]);

    //     }
    // }

    /**
     * 文章置顶
     * @adminMenu(
     *     'name'   => '文章置顶',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章置顶',
     *     'param'  => ''
     * )
     */
    public function top()
    {
        $param           = $this->request->param();
        $losePostModel = new LosePostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $losePostModel->where(['id' => ['in', $ids]])->update(['is_top' => 1]);

            //操作日志
            admin_log('', '', 'article_top_yes');
            $this->success("置顶成功！", '');

        }

        if (isset($_POST['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $losePostModel->where(['id' => ['in', $ids]])->update(['is_top' => 0]);

            //操作日志
            admin_log('', '', 'article_top_no');
            $this->success("取消置顶成功！", '');
        }
    }

    /**
     * 文章推荐
     * @adminMenu(
     *     'name'   => '文章推荐',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章推荐',
     *     'param'  => ''
     * )
     */
    public function recommend()
    {
        $param           = $this->request->param();
        $losePostModel = new LosePostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $losePostModel->where(['id' => ['in', $ids]])->update(['recommended' => 1]);

            //操作日志
            admin_log('', '', 'article_recommend_yes');
            $this->success("推荐成功！", '');

        }
        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $losePostModel->where(['id' => ['in', $ids]])->update(['recommended' => 0]);

            //操作日志
            admin_log('', '', 'article_recommend_no');
            $this->success("取消推荐成功！", '');

        }
    }

    /**
     * 文章排序
     * @adminMenu(
     *     'name'   => '文章排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders(Db::name('lose_category_post'));

        //操作日志
        admin_log('', '', 'article_list_order');

        $this->success("排序更新成功！", '');
    }

    // 文章批量移动
    public function move()
    {
        if ( $this->request->isPost()){
            $ids         = $this->request->param('ids/s');
            $old_cat_id  = $this->request->param('old_cat_id', 0, 'intval');
            $category_id = $this->request->param('categories', 0, 'intval');

            if(!empty($ids) && !empty($old_cat_id) && !empty($category_id)){

                if( $old_cat_id != $category_id ){
                    $ids = explode(',', $ids);
                    foreach ($ids as $id){
                        Db::name('LoseCategoryPost')->where(['post_id'=>$id,'category_id'=>$old_cat_id])->delete();
                        $find_relation_count=Db::name('LoseCategoryPost')->where(['post_id'=>$id,'category_id'=>$category_id])->count();
                        if($find_relation_count==0){
                            Db::name('LoseCategoryPost')->insert(['post_id'=>$id,'category_id'=>$category_id]);
                        }
                    }
                }

                //操作日志
                admin_log('', '', 'article_move');
                $this->success("移动成功！");
            }
        }else{
            $loseCategoryModel = new LoseCategoryModel();
            $categoryTree        = $loseCategoryModel->adminCategoryTree();
            $this->assign('category_tree', $categoryTree);
            return $this->fetch();
        }
    }
    
    // 文章批量复制
    public function copy()
    {
        if ( $this->request->isPost()){
            $ids         = $this->request->param('ids/s');
            $category_id = $this->request->param('categories', 0, 'intval');

            if( !empty($ids) && !empty($category_id) ){
                $loseCategoryModel = new LoseCategoryModel();
                $ids         = explode(',', $ids);
                $uid         = cmf_get_current_admin_id();
                $term_count  = $loseCategoryModel->where('id', $category_id)->count();

                if( $term_count == 0 ){
                    $this->error('分类不存在！');
                }
                
                $losePostModel = new LosePostModel();
                $data            = array();
                foreach ($ids as $id){
                    $find_post = $losePostModel->find($id)->toArray();
                    if($find_post){
                        unset($find_post['id']);
                        $find_post['user_id']        = $uid;
                        $find_post['published_time'] = time();
                        $find_post['update_time']    = time();
                        $find_post['create_time']    = time();
                        $find_post['more']           = json_encode($find_post['more']);
                        $post_id                     = $losePostModel->insertGetId($find_post);
                        if($post_id>0){
                            array_push($data, ['post_id'=>$post_id, 'category_id'=>$category_id]);
                        }
                    }
                }

                if ( Db::name('LoseCategoryPost')->insertAll($data) !== false) {
                    //操作日志
                    admin_log('', '', 'article_copy');

                    $this->success("复制成功！");
                } else {
                    $this->error("复制失败！");
                }
            }
        }else{
            $loseCategoryModel = new LoseCategoryModel();
            $categoryTree        = $loseCategoryModel->adminCategoryTree();
            $this->assign('category_tree', $categoryTree);
            return $this->fetch();
        }
    }

    /**
     * 待审核文章列表
     * @adminMenu(
     *     'name'   => '待审核内容',
     *     'parent' => 'index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '待审核文章列表',
     *     'param'  => ''
     * )
     */
    public function checkList()
    {
        $param      = $this->request->param();
        $categoryId = $this->request->param('category', 0, 'intval');
        $stepIndex  = $this->request->param('step_index', 1, 'intval');

        $param['sort_by']     = $this->request->param('sort_by','id','trim');
        $param['list_order']  = $this->request->param('list_order','DESC','trim');

        $loseCategoryModel = new LoseCategoryModel();

        //当前分类信息
        if( empty($categoryId) ){
            //默认分类ID
            $category = $loseCategoryModel
                     -> field('id,audit_id')
                     -> where('delete_time',0)
                     -> where('audit_id','>',0)
                     -> order("id ASC")
                     -> find();
            $categoryId = $param['category'] =$category['id'];
        }else{
            $category = $loseCategoryModel
                     -> field('id,audit_id')
                     -> where('id',$categoryId)
                     -> order("id ASC")
                     -> find();
        }

        //分类树
        $categoryTree = $loseCategoryModel->adminCategoryTree($categoryId, 0, 0, 1);

        $noAuthKey = $authKey = [];
        // 分类有选择审核流程
        if( !empty($category['audit_id']) ){
            //角色id
            $role_id  = session('ROLE_ID');
            //该流程下的所有审核步骤
            $stepList = Db::name('audit_flow_step')
                     -> where('audit_id',$category['audit_id'])
                     -> order('step_index asc')
                     -> select()
                     -> toArray();

            // 审核流程下存在审核步骤
            if( !empty($stepList) ){

                foreach ($stepList as $k => $v) {
                    //若当前登录的不是超级管理员，判断是否拥有该步骤的权限
                    if( $role_id!=1 ){
                        //分割拥有该步骤权限的角色id
                        $auth_role_id = explode(',',$v['auth_role_id']);

                        if( !in_array($role_id, $auth_role_id) ){
                            $noAuthKey[] = $v['step_index'];  //没有权限的审核步骤
                        }
                    }

                    //构建数组，用于创建审核步骤select框
                    $haveStep[$v['step_index']] = $v['step_name'];
                }

                $allAuthKey = array_keys($haveStep);                  //所有审核步骤
                $authKey    = array_diff($allAuthKey, $noAuthKey);    //有权限的审核步骤

                //若当前选择的步骤序号大于该流程下最大的步骤序号，则重置为1(第一个审核步骤)
                $lastIndex = end($allAuthKey);
                $stepIndex = ($stepIndex > $lastIndex) ? 1 : $stepIndex;

                //若当前步骤在非拥有权限步骤的集合中
                if( in_array($stepIndex, $noAuthKey) ){
                    //若拥有权限步骤集合不为空，重置当前步骤;否则清空步骤，不查询待审核数据
                    $stepIndex = !empty($authKey) ? current($authKey) : 0;
                }

                //待审核文章列表
                if( !empty($stepIndex) ){
                    $param['post_status'] = ['=',$stepIndex];
                    $postService = new PostService();
                    $data        = $postService->adminArticleList($param);
                    $articles    = $data->items();
                    
                    /**
                     * 文章是否拥有编辑和删除的权限
                     * 只要该文章所属的某个分类中拥有编辑或删除权限即可以操作该文章
                     */
                    $articleEdit = cmf_auth_check(cmf_get_current_admin_id(), 'lose/adminarticle/edit');
                    
                    $userId = cmf_get_current_admin_id();
                    foreach ($articles as $k => &$v) {
                        // 若为超级管理员可编辑和删除
                        if( $roleId == 1 ){
                            $v['is_edit'] = 1;
                        }else{
                            $v['is_edit'] = 0;
                            // 若不是超级管理员，仅可操作自己添加的文章
                            // if( $v['user_id'] != $userId )  continue;
                            if( !$articleEdit )             continue;

                            // 该文章所属的所有分类
                            $categoryIds  = db('lose_category_post')->where('post_id', $v['id'])->column('category_id');
                            if( $articleEdit ){
                                // 该文章所属的某个分类是否拥有编辑的操作权限
                                $v['is_edit']   = check_cat_priv($categoryIds,'edit');
                            }
                        }
                    }
                    
                    //追加参数，用于分页
                    $data->appends($param);
                    $this->assign('articles', $articles);
                    $this->assign('page', $data->render());
                }
            }
        }

        $haveStepList = html_options($haveStep, $stepIndex, $noAuthKey);
        $this->assign('have_step_list', $haveStepList);     //拥有的步骤列表

        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        // $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');

        //当前排序依据
        $sort_flag  = sort_flag($param);
        $this->assign($sort_flag['tag'], $sort_flag['img']);

        $this->assign('step_index', $stepIndex);            //当前所在步骤
        $this->assign('category_tree', $categoryTree);      //分类树
        $this->assign('category', $categoryId);             //当前分类id
        $this->assign("filter",$param);

        return $this->fetch();
    }

    /**
     * 文章发布
     * @adminMenu(
     *     'name'   => '文章发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章发布',
     *     'param'  => ''
     * )
     */
    public function openshow()
    {
        $param           = $this->request->param();

        $ids = $this->request->param('ids/a');

        $where = [
            'a.post_id' => ['in', $ids],
        ];

        if( session('ROLE_ID') != 1 ){
            $where['b.post_status'] = 99;
        }

        if (isset($param['ids']) && isset($param["yes"])) {
            db('lose_category_post')
            ->alias('a')
            ->join('lose_post b','a.post_id = b.id')
            ->where($where)
            ->update(['a.is_show' => 1]);

            //操作日志
            admin_log('', '', 'article_open_show_yes');
            // $this->success("发布成功！", '');
        }

        if (isset($param['ids']) && isset($param["no"])) {
            db('lose_category_post')
            ->alias('a')
            ->join('lose_post b','a.post_id = b.id')
            ->where($where)
            ->update(['a.is_show' => 0]);

            //操作日志
            admin_log('', '', 'article_open_show_no');

        }
            $this->success("操作成功！", '');

    }

    //通过审核
    public function pass(){
        $ids        = $this->request->param('ids/a');                   //文章id数组
        $categoryId = $this->request->param('category', 0, 'intval');   //分类id
        $stepIndex  = $this->request->param('step_index', 1, 'intval'); //审核状态

        if( $stepIndex == -1 ){
            parent::passStep(Db::name('lose_post'), $stepIndex);
            //操作日志
            admin_log('', '', 'article_not_pass');
        }else{
            //获取当前分类所使用的审核流程
            $loseCategoryModel = new LoseCategoryModel();
            $audit_id = $loseCategoryModel->where('id',$categoryId)->value('audit_id');

            //该流程下的所有审核步骤
            $maxStepIndex = Db::name('audit_flow_step')
                         -> where('audit_id',$audit_id)
                         -> max('step_index');

            //是否已超过最终步骤
            if( $maxStepIndex>$stepIndex ){
                $status = $stepIndex+1;
            }else {
                $status = 99;
            }
            
            // 修改文章审核状态
            parent::passStep(Db::name('lose_post'), $status);

            //操作日志
            admin_log('', '', 'article_pass');
        }

        $this->success("操作成功！",'');
    }

    /**
     *
     * 导出Excel
     */
    public function export(){//导出Excel

        $filter = $this->request->param();
        $order  = "b.category_id ASC, b.list_order DESC, a.published_time DESC, b.post_id DESC";
        $where  = [
            'a.post_type'   => 1,
            'a.create_time' => ['>=', 0],
            'a.delete_time' => 0,
        ];

        // $siteConfig      = cmf_get_site_info();
        // $authMode        = $siteConfig['auth_mode'];

        //是否指定分类
        $category = empty($filter['category']) ? 0 : intval($filter['category']);
        if( empty($category) ){
            //获取方式排序为分类树形式的所有分类id
            $loseCategoryModel = new LoseCategoryModel();
            $categoryIds         = $loseCategoryModel->adminCategoryTableTree(0,"\$id,");
            $categoryIds         = explode(',', $categoryIds);

            // 若不是超级管理员，只获取有导出权限的分类
            if( session('ROLE_ID') != 1 ){
                //获取有导出权限的分类
                $operateIds  = get_cat_priv('export', 'lose_category');
                if( empty($operateIds) ){
                    $this->error(lang('NO_AUTH'));
                }

                //有权限的分类数组和所有分类数组取交集，用于得到有权限的分类id集并保持排序
                $categoryIds = array_intersect($operateIds, $categoryIds);
            }
            $where['b.category_id'] = ['in', $categoryIds];
        }else{
            // 该角色当前分类是否有导出权限
            if( !check_cat_priv($category, 'export') ){
                $this->error(lang('NO_AUTH'));
            }
            $where['b.category_id'] = ['eq', $category];
        }


        $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
        $endTime   = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
        if (!empty($startTime) && !empty($endTime)) {
            $where['a.published_time'] = [['>= time', $startTime], ['<= time', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['a.published_time'] = ['>= time', $startTime];
            }
            if (!empty($endTime)) {
                $where['a.published_time'] = ['<= time', $endTime];
            }
        }

        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if (!empty($keyword)) {
            $where['a.post_title'] = ['like', "%$keyword%"];
        }

        $join = [
            ['__PORTAL_CATEGORY_POST__ b', 'a.id = b.post_id'],
            ['__PORTAL_CATEGORY__ c', 'b.category_id = c.id'],
            ['__USER__ u', 'a.user_id = u.id'],
        ];

        $losePostModel = new LosePostModel();
        $data = $losePostModel->alias('a')->field($field)
             -> field('post_title, c.name, u.user_login as author, post_hits, a.published_time, a.update_time, c.id')
             -> join($join)
             -> where($where)
             -> order($order)
             -> select()
             -> toArray();
        
        if( empty($categoryIds) ){
            // 指定了分类
            foreach ($data as $k => &$v) {
                $v['published_time'] = date('Y/m/d H:i', $v['published_time']);
                $v['update_time']    = date('Y/m/d H:i', $v['update_time']);
            }
            $xlsData = $data;
        }else{
            // 没有指定分类时，按照分类树的排序，创建要导出的数据数组
            foreach ($categoryIds as $k => $v) {
                foreach ($data as $key => $val) {
                    if( $v == $val['id'] ){
                        $val['published_time'] = date('Y/m/d H:i', $val['published_time']);
                        $val['update_time']    = date('Y/m/d H:i', $val['update_time']);
                        $xlsData[] = $val;
                    }
                }
            }
        }

        //操作日志
        admin_log('', '', 'article_export');

        $xlsName  = "文章点击量统计_".date('YmdHis');
        $xlsCell  = array(
            array('post_title','标题'),
            array('name','分类'),
            array('author','作者'),
            array('post_hits','点击量'),
            array('published_time','发布时间'),
            array('update_time','更新时间'),
        );
        
        exportExcel($xlsName,$xlsCell,$xlsData);
    }
}
